package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.vo.HandleOptionVo;
import com.cskaoyan.market.vo.OrderGoodsListVo;
import com.cskaoyan.market.vo.OrderInfoVo;
import com.cskaoyan.market.vo.OrderListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    //订单列表
    @Override
    public List<OrderListVo> getOrderList(Integer showType, Integer page, Integer limit, Integer userId) {

        //根据showtype和session的userId分类订单列表,删除的订单不显示
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        if (showType==1){
            marketOrderExample.or().andOrderStatusEqualTo((short) 101).andDeletedEqualTo(false).andUserIdEqualTo(userId);
        }else if (showType==2){
            marketOrderExample.or().andOrderStatusEqualTo((short) 201).andDeletedEqualTo(false).andUserIdEqualTo(userId);
        }else if (showType==3){
            marketOrderExample.or().andOrderStatusEqualTo((short) 301).andDeletedEqualTo(false).andUserIdEqualTo(userId);
        }else if (showType==4){
            ArrayList<Short> shorts = new ArrayList<>();
            shorts.add((short) 401);
            shorts.add((short) 402);
            marketOrderExample.or().andOrderStatusIn(shorts).andDeletedEqualTo(false).andUserIdEqualTo(userId);
        }else {
            marketOrderExample.or(). andDeletedEqualTo(false).andUserIdEqualTo(userId);
        }
        List<MarketOrder> marketOrderList = marketOrderMapper.selectByExample(marketOrderExample);



//        PageHelper.startPage(page,limit);



        ArrayList<OrderListVo> orderListVos = new ArrayList<>();
        for (MarketOrder marketOrder : marketOrderList) {
            Short status = marketOrder.getOrderStatus();
            HandleOptionVo handleOptionVo = getHandleOptionVo(status);
            OrderListVo orderListVo = new OrderListVo();
            orderListVo.setActualPrice(marketOrder.getActualPrice());
            orderListVo.setAftersaleStatus(marketOrder.getAftersaleStatus());

            Integer id = marketOrder.getId();
            List<OrderGoodsListVo> orderGoodsList = getOrderGoodsList(id);
            orderListVo.setGoodsList(orderGoodsList);

            orderListVo.setHandleOption(handleOptionVo);
            orderListVo.setId(marketOrder.getId());
            orderListVo.setIsGroupin(false);
            orderListVo.setOrderSn(marketOrder.getOrderSn());

            String string = exchangeCodeToString(status);
            orderListVo.setOrderStatusText(string);

            orderListVos.add(orderListVo);
        }
        return orderListVos;
    }

    //订单详情
    @Override
    public Map<String,Object> getOrderDetailList(Integer orderId) {
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.or().andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);

        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.or().andIdEqualTo(orderId);
        MarketOrder marketOrder = marketOrderMapper.selectOneByExample(marketOrderExample);

        Short orderStatus = marketOrder.getOrderStatus();
        HandleOptionVo handleOptionVo = getHandleOptionVo(orderStatus);

        OrderInfoVo orderInfoVo = new OrderInfoVo();
        orderInfoVo.setActualPrice(marketOrder.getActualPrice());
        orderInfoVo.setAddTime(marketOrder.getAddTime());
        orderInfoVo.setAddress(marketOrder.getAddress());
        orderInfoVo.setAftersaleStatus(marketOrder.getAftersaleStatus());
        orderInfoVo.setConsignee(marketOrder.getConsignee());
        orderInfoVo.setCouponPrice(marketOrder.getCouponPrice());
        orderInfoVo.setFreightPrice(marketOrder.getFreightPrice());
        orderInfoVo.setGoodsPrice(marketOrder.getGoodsPrice());
        orderInfoVo.setHandleOption(handleOptionVo);
        orderInfoVo.setId(marketOrder.getId());
        orderInfoVo.setMessage(marketOrder.getMessage());
        orderInfoVo.setMobile(marketOrder.getMobile());
        orderInfoVo.setOrderSn(marketOrder.getOrderSn());
        if(orderStatus==301||orderStatus==401||orderStatus==402){
            orderInfoVo.setExpCode(marketOrder.getShipChannel());
            orderInfoVo.setExpName(getExpNameByExpCode(marketOrder.getShipChannel()));
            orderInfoVo.setExpNo(marketOrder.getShipSn());
        }

        String string = exchangeCodeToString(orderStatus);
        orderInfoVo.setOrderStatusText(string);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("orderGoods",marketOrderGoods);
        hashMap.put("orderInfo",orderInfoVo);
        ArrayList<Object> list = new ArrayList<>();
        hashMap.put("expressInfo",list);
        return hashMap;
    }
    //订单退款
    @Override
    public void orderRefund(Integer orderId) {
        LocalDateTime dateTime = LocalDateTime.now();

        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.or().andIdEqualTo(orderId);

        //退款金额等于实际支付的
        MarketOrder marketOrder = new MarketOrder();
        MarketOrder marketOrder1 = marketOrderMapper.selectOneByExampleSelective(marketOrderExample, MarketOrder.Column.actualPrice);
        BigDecimal actualPrice = marketOrder1.getActualPrice();
        marketOrder.setRefundAmount(actualPrice);
        marketOrder.setRefundType("微信退款接口");

//        //优惠券原路返回,状态改为未使用
//        MarketCouponUser marketCouponUser = new MarketCouponUser();
//        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
//        marketCouponUserExample.or().andOrderIdEqualTo(orderId);
//        marketCouponUser.setStatus((short) 0);
//        marketCouponUser.setUpdateTime(dateTime);
//        marketCouponUserMapper.updateByExampleSelective(marketCouponUser,marketCouponUserExample);

        //获取并修改当前时间
        marketOrder.setRefundTime(dateTime);
        marketOrder.setUpdateTime(dateTime);
        //修改订单状态码
        Short s = 202;
        marketOrder.setOrderStatus(s);

        marketOrderMapper.updateByExampleSelective(marketOrder,marketOrderExample);
    }

    //订单删除，只把order表的deleted列改成ture即可。
    @Override
    public void orderDelete(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setDeleted(true);

        //获取当前时间
        LocalDateTime dateTime = LocalDateTime.now();
        marketOrder.setUpdateTime(dateTime);

        //根据orderid更新order表的deleted属性
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.or().andIdEqualTo(orderId);
        marketOrderMapper.updateByExampleSelective(marketOrder,marketOrderExample);
    }

    //订单取消，修改订单状态码为102：用户取消。更新时间
    @Override
    public void orderCancel(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        Short s = 102;
        marketOrder.setOrderStatus(s);
        LocalDateTime time = LocalDateTime.now();
        marketOrder.setUpdateTime(time);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.or().andIdEqualTo(orderId);
        marketOrderMapper.updateByExampleSelective(marketOrder,marketOrderExample);
    }
    //订单提交
    @Override
    public void orderSubmit(Map<String, Object> map) {
        LocalDateTime Time = LocalDateTime.now();
        //更新，将购物车里的商品添加到order表
        MarketOrder marketOrder = new MarketOrder();

        MarketAddressExample marketAddressExample = new MarketAddressExample();
        marketAddressExample.or().andIdEqualTo((Integer) map.get("addressId"));
        MarketAddress marketAddress = marketAddressMapper.selectOneByExample(marketAddressExample);

        marketOrder.setUserId(marketAddress.getUserId());
        //根据时间生成一个订单编号
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String newsNo = Time.format(fmt);
        marketOrder.setOrderSn(newsNo);
        marketOrder.setOrderStatus((short) 101);
        marketOrder.setAftersaleStatus((short) 0);
        marketOrder.setConsignee(marketAddress.getName());
        marketOrder.setMobile(marketAddress.getTel());
        marketOrder.setAddress(marketAddress.getAddressDetail());
        marketOrder.setMessage((String) map.get("message"));

        //商品总价
        //查询购物车里被checked的商品,且delete为false
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.or().andCheckedEqualTo(true).andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        BigDecimal sum = new BigDecimal("0.00000");
        for (MarketCart marketCart : marketCarts) {
            BigDecimal price = marketCart.getPrice();
            sum.add(price);
        }
        marketOrder.setGoodsPrice(sum);

        //优惠券价格
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        marketCouponExample.or().andIdEqualTo((Integer) map.get("couponId"));
        MarketCoupon marketCoupon = marketCouponMapper.selectOneByExampleSelective(marketCouponExample, MarketCoupon.Column.discount);

        BigDecimal discount = new BigDecimal(0);
        if (marketCoupon == null) {
            marketCoupon = new MarketCoupon();
            marketCoupon.setDiscount(new BigDecimal("0"));
            discount = marketCoupon.getDiscount();
        } else {
            discount = marketCoupon.getDiscount();
        }
        marketOrder.setCouponPrice(discount);

        //运费
        if (sum.compareTo(new BigDecimal("88"))>=0){
            marketOrder.setFreightPrice(new BigDecimal("0"));
            //实际支付了多少钱
            marketOrder.setActualPrice(sum.subtract(discount));
        }else {
            marketOrder.setFreightPrice(new BigDecimal("8"));
            marketOrder.setActualPrice(sum.subtract(discount).add(new BigDecimal("8")));
            marketOrder.setOrderPrice(sum.subtract(discount).add(new BigDecimal("8")));
        }

        //获取当前时间,更新时间，添加时间
        marketOrder.setAddTime(Time);
        marketOrder.setUpdateTime(Time);
        BigDecimal bigDecimal = new BigDecimal("0");
        marketOrder.setIntegralPrice(bigDecimal);
        marketOrder.setGrouponPrice(bigDecimal);
        marketOrderMapper.insertSelective(marketOrder);

        Integer id = marketOrder.getId();


        //更新coupon-user表，如果用了要更改优惠券属性, 优惠券状态改为已使用
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        marketCouponUser.setUserId(marketAddress.getUserId());
        marketCouponUser.setStatus((short) 1);
        marketCouponUser.setUsedTime(Time);
        marketCouponUser.setUpdateTime(Time);
        marketCouponUser.setOrderId(id);
        marketCouponUserMapper.updateByExampleSelective(marketCouponUser,marketCouponUserExample);

        //更新cart表，购物车提交后，应更新删除提交的商品,并更新日期
        MarketCart marketCart1 = new MarketCart();
        marketCart1.setUserId(marketAddress.getUserId());
        marketCart1.setDeleted(true);
        marketCart1.setUpdateTime(Time);
        marketCartMapper.updateByExampleSelective(marketCart1,marketCartExample);

        //更新，将购物车里的商品添加到order-goods表
        for (MarketCart marketCart : marketCarts) {
            MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
            marketOrderGoods.setNumber(marketCart.getNumber());

            marketOrderGoods.setAddTime(Time);
            marketOrderGoods.setUpdateTime(Time);

            //通过选中的购物车商品的goodsid查询商品表信息
            Integer goodsId = marketCart.getGoodsId();
            MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
            marketGoodsExample.or().andIdEqualTo(goodsId);
            MarketGoods marketGoods = marketGoodsMapper.selectOneByExample(marketGoodsExample);

            marketOrderGoods.setGoodsId(marketGoods.getId());
            marketOrderGoods.setGoodsName(marketGoods.getName());
            marketOrderGoods.setGoodsSn(marketGoods.getGoodsSn());

            //通过选中的购物车商品的productId查询商品货品表信息
            Integer productId = marketCart.getProductId();
            MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
            marketGoodsProductExample.or().andIdEqualTo(productId);
            MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectOneByExample(marketGoodsProductExample);

            marketOrderGoods.setProductId(marketGoodsProduct.getId());
            marketOrderGoods.setPrice(marketGoodsProduct.getPrice());
            marketOrderGoods.setSpecifications(marketGoodsProduct.getSpecifications());
            marketOrderGoods.setPicUrl(marketGoodsProduct.getUrl());

            marketOrderGoodsMapper.insertSelective(marketOrderGoods);
        }
    }

    //订单评论，更新comment表中，修改order表中的comments的待评价商品数，
    // 修改order-goods表的评论id,评价之后不能再评价，去掉评价按钮，
    @Override
    public void orderComment(Map<String, Object> map,Integer id) {
        MarketComment marketComment = new MarketComment();
        marketComment.setUserId(id);
        marketComment.setContent((String) map.get("content"));
        marketComment.setHasPicture((Boolean) map.get("hasPicture"));

        ArrayList<String> picUrls = (ArrayList<String>) map.get("picUrls");
        String[] array = picUrls.toArray(new String[picUrls.size()]);
        marketComment.setPicUrls(array);

        Integer star = (Integer) map.get("star");
        Short a = Short.valueOf(star.shortValue());
        marketComment.setStar(a);

        LocalDateTime Time = LocalDateTime.now();
        marketComment.setAddTime(Time);
        marketComment.setUpdateTime(Time);

        //设置comment表中的valueid
        MarketOrderGoodsExample marketOrderGoodsExample2 = new MarketOrderGoodsExample();
        marketOrderGoodsExample2.or().andIdEqualTo((Integer) map.get("orderGoodsId"));
        MarketOrderGoods marketOrderGoods1 = marketOrderGoodsMapper.selectOneByExampleSelective(marketOrderGoodsExample2, MarketOrderGoods.Column.goodsId);
        Integer goodsId = marketOrderGoods1.getGoodsId();
        marketComment.setValueId(goodsId);
        marketCommentMapper.insertSelective(marketComment);

        //修改ordergoods表中的comments(评论的id)
        Integer commentId = marketComment.getId();
        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        marketOrderGoods.setComment(commentId);
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.or().andIdEqualTo((Integer) map.get("orderGoodsId"));
        marketOrderGoodsMapper.updateByExampleSelective(marketOrderGoods,marketOrderGoodsExample);


        //修改order表中的comments的待评价商品数
        MarketOrderGoodsExample marketOrderGoodsExample1 = new MarketOrderGoodsExample();
        marketOrderGoodsExample1.or().andIdEqualTo((Integer) map.get("orderGoodsId"));
        MarketOrderGoods marketOrderGoods2 = marketOrderGoodsMapper.selectOneByExampleSelective(marketOrderGoodsExample1);
        Integer orderId = marketOrderGoods2.getOrderId();

        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.or().andIdEqualTo(orderId);
        MarketOrder marketOrder = marketOrderMapper.selectOneByExampleSelective(marketOrderExample, MarketOrder.Column.comments);
        marketOrder.setComments((short) (marketOrder.getComments()-1));
        marketOrderMapper.updateByExampleSelective(marketOrder,marketOrderExample);
    }

    //未评论订单点击评论时获取商品信息
    @Override
    public MarketOrderGoods orderGoods(Integer goodsId) {
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.or().andGoodsIdEqualTo(goodsId);
        MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectOneByExample(marketOrderGoodsExample);
        return marketOrderGoods;
    }

    //订单确认收货，order表添加收货时间,更新时间，修改订单状态，根据商品数量更新商品待评论数量
    @Override
    public void orderConfirm(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        LocalDateTime time = LocalDateTime.now();

        marketOrder.setConfirmTime(time);
        marketOrder.setUpdateTime(time);
        marketOrder.setOrderStatus((short) 401);

        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.or().andIdEqualTo(orderId);
        long l = marketOrderGoodsMapper.countByExample(marketOrderGoodsExample);
        marketOrder.setComments((short) l);

        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.or().andIdEqualTo(orderId);
        marketOrderMapper.updateByExampleSelective(marketOrder,marketOrderExample);
    }

    public List<OrderGoodsListVo> getOrderGoodsList(Integer i){
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.or().andOrderIdEqualTo(i);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);

        List<OrderGoodsListVo> listVos = new ArrayList<>();
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            OrderGoodsListVo orderGoodsListVo = new OrderGoodsListVo();
            orderGoodsListVo.setGoodsName(marketOrderGood.getGoodsName());
            orderGoodsListVo.setId(marketOrderGood.getId());
            orderGoodsListVo.setNumber(marketOrderGood.getNumber());
            orderGoodsListVo.setPicUrl(marketOrderGood.getPicUrl());
            orderGoodsListVo.setPrice(marketOrderGood.getPrice());
            orderGoodsListVo.setSpecifications(marketOrderGood.getSpecifications());

            listVos.add(orderGoodsListVo);
        }
        return listVos;
    }

    public HandleOptionVo getHandleOptionVo(Short statusCode){
        if(statusCode ==101){
            HandleOptionVo handleOptionVo101 = new HandleOptionVo(false, true, false, false, false, true, false, false);
            return handleOptionVo101;
        }
        if(statusCode ==102){
            HandleOptionVo handleOptionVo102 = new HandleOptionVo(false, false, false, false, true, false, false, false);
            return handleOptionVo102;
        }
        if(statusCode ==103){
            HandleOptionVo handleOptionVo103 = new HandleOptionVo(false, false, false, false, true, false, false, false);
            return handleOptionVo103;
        }
        if(statusCode ==201){
            HandleOptionVo handleOptionVo201 = new HandleOptionVo(false, false, false, false, false, false, false, true);
            return handleOptionVo201;
        }
        if(statusCode ==202){
            HandleOptionVo handleOptionVo202 = new HandleOptionVo(false, false, false, false, false, false, false, false);
            return handleOptionVo202;
        }
        if(statusCode ==203){
            HandleOptionVo handleOptionVo203 = new HandleOptionVo(false, false, false, false, true, false, true, false);
            return handleOptionVo203;
        }
        if(statusCode ==301){
            HandleOptionVo handleOptionVo301 = new HandleOptionVo(false, false, false, true, false, false, false, true);
            return handleOptionVo301;
        }
        if(statusCode ==401){
            HandleOptionVo handleOptionVo401 = new HandleOptionVo(true, false, true, false, true, false, true, false);
            return handleOptionVo401;
        }
        if (statusCode ==402) {
            HandleOptionVo handleOptionVo402 = new HandleOptionVo(true, false, true, false, true, false, true, false);
            return handleOptionVo402;
        }

        HandleOptionVo handleOptionV500 = new HandleOptionVo(false, false, false, false, false, false, false, false);

        return handleOptionV500;
    }

    public String exchangeCodeToString(Short statusCode){
        if(statusCode ==101){
            return "未付款";
        }
        if(statusCode ==102){
            return "用户取消";
        }
        if(statusCode ==103){
            return "系统取消";
        }
        if(statusCode ==201){
            return "已付款";
        }
        if(statusCode ==202){
            return "申请退款";
        }
        if(statusCode ==203){
            return "已退款";
        }
        if(statusCode ==301){
            return "已发货";
        }
        if(statusCode ==401){
            return "用户收货";
        }
        if(statusCode ==402){
            return "系统收货";
        }
        return "状态异常（无此状态码）";
    }

    public String getExpNameByExpCode(String s){
        if (s.equals("ZTO")){
            return "中通快递";
        }
        if (s.equals("YTO")){
            return "圆通快递";
        }
        if (s.equals("YD")){
            return "韵达快递";
        }
        if (s.equals("YZPY")){
            return "邮政快递包裹";
        }
        if (s.equals("EMS")){
            return "EMS";
        }
        if (s.equals("DBL")){
            return "德邦快递";
        }
        if (s.equals("FAST")){
            return "快捷快递";
        }
        if (s.equals("ZJS")){
            return "宅急送";
        }
        if (s.equals("TNT")){
            return "TNT快递";
        }
        if (s.equals("UPS")){
            return "UPS";
        }
        if (s.equals("DHL")){
            return "DHL";
        }
        if (s.equals("FEDEX")){
            return "FEDEX联邦(国内件)";
        }
        if (s.equals("FEDEX_GJ")){
            return "FEDEX联邦(国际件)";
        }
        return "未知快递公司";
    }
}